package com.shr.lease.web.app.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shr.lease.common.constant.RedisConstant;
import com.shr.lease.common.context.LoginUser;
import com.shr.lease.common.context.LoginUserContext;
import com.shr.lease.common.exception.LeaseException;
import com.shr.lease.common.result.ResultCodeEnum;
import com.shr.lease.common.utils.JWTUtil;
import com.shr.lease.common.utils.VerifyCodeUtil;
import com.shr.lease.model.entity.UserInfo;
import com.shr.lease.model.enums.BaseStatus;
import com.shr.lease.web.app.service.LoginService;
import com.shr.lease.web.app.service.SmsService;
import com.shr.lease.web.app.service.UserInfoService;
import com.shr.lease.web.app.vo.user.LoginVo;
import com.shr.lease.web.app.vo.user.UserInfoVo;
import jakarta.annotation.Resource;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private SmsService smsService;


    @Override
    public String login(LoginVo loginVo) {

        //1、参数校验
        if (StringUtils.isBlank(loginVo.getPhone())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        if (StringUtils.isBlank(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
        //2、判断验证码是否过期
        String key = RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone();
        String redisCode = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(redisCode)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
        //3、判断验证码是否正确
        if (!redisCode.equals(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        //4、使用phone从数据库中查询用户信息若为空则新建用户
        UserInfo userInfo = userInfoService.getOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getPhone, loginVo.getPhone())
        );
        if (userInfo == null) {
            userInfo = UserInfo.builder()
                    .phone(loginVo.getPhone())
                    .nickname("用户-" + loginVo.getPhone()) //默认别名
                    .status(BaseStatus.ENABLE) //默认状态启用
                    .avatarUrl("192.168.15.129:9000/lease/fall.jpg") //默认头像 --> 放在minio服务器上
                    .password(DigestUtils.sha256Hex("123456")) //默认密码
                    .build();
            //新建用户并插入数据库
            userInfoService.save(userInfo);
        }else if (userInfo.getStatus() == BaseStatus.DISABLE){ //5、判断用户是否被禁用
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        //6、创建JWT返回
        return JWTUtil.generateToken(userInfo.getId(),userInfo.getNickname());
    }

    @Override
    public void getCode(String phone) {
        //1、检查手机号是否为空
        if (StringUtils.isBlank(phone)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        //2、检查redis中是否存在该手机号的key
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        Boolean hasKey = stringRedisTemplate.hasKey(key);
        if(hasKey){
            //存在，则检查其存在时间
            Long expire = stringRedisTemplate.getExpire(key);
            if (RedisConstant.APP_LOGIN_CODE_TTL_SEC - expire < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC){
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }
        //3、发送短信，并将验证码存入Redis
        String verifyCode = VerifyCodeUtil.generateVerifyCode(6);
        smsService.snedCode(phone,verifyCode);
        stringRedisTemplate.opsForValue().set(key,verifyCode,RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);


    }

    @Override
    public UserInfoVo info() {
        LoginUser loginUser = LoginUserContext.getLoginUser();
        UserInfo userInfo = userInfoService.getOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getId, loginUser.getUserId())
                .select(UserInfo::getAvatarUrl, UserInfo::getNickname)
        );
        return UserInfoVo.builder()
                .nickname(userInfo.getNickname())
                .avatarUrl(userInfo.getAvatarUrl())
                .build();
    }
}
